<template>
	<view style="background-color: #f0f2f6">
		<!-- 顶部tap切换 -->
		<wuc-tab id="tab" :tab-list="tabList3" textFlex :tabCur.sync="TabCur3" tab-class="text-center text-black bg-white wuc-tab fixed"
		 select-class="text-blue" @change="tabChange"></wuc-tab>
		 
		<scroll-view scroll-y :style="{height:(height-51)+'px'}">
			<!-- 消息列表页 -->
			<view v-if="TabCur3==0">
				<!-- 搜索框 -->
				<view class="search-input"><label class="iconfont icon-sousuo" />
					<input type="text" confirm-type="search" v-model="search" class="font-size30" placeholder="输入你要搜索的内容" />
				</view>
				<!-- 固定模块 -->
				<view style="background-color: #FFFFFF;">
					<!-- 通知公告 -->
					<view class="uni-list-cell uni-list-cell-last" hover-class="uni-list-cell-hover" @tap="noticeInfo">
						<view class="cell-navigate">
							<view class="uni-list-data gongao-back">
								<label class="iconfont icon-gonggao icon-label-lin" />
							</view>
							<view class="uni-item-left">
								<view class="color-3A3A3A font-size30">通知公告</view>
								<view class="color-9A9A9A font-size24">{{noticeMsg.noticeText|overstep}}</view>
							</view>
							<view class="uni-item-right">
								<view class="color-9A9A9A">{{noticeMsg.noticeDate}}</view>
								<view class="height-50">
									<view class="iconlabel" v-show="isNotices">{{noticeMsg.noticeCount}}</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 系统消息 -->
					<view class="uni-list-cell uni-list-cell-last" hover-class="uni-list-cell-hover" @tap="systemInfo">
						<view class="cell-navigate">
							<view class="uni-list-data xiaoxi-back">
								<label class="iconfont icon-tongzhi icon-label-lin" />
							</view>
							<view class="uni-item-left">
								<view class="color-3A3A3A font-size30">系统消息</view>
								<view class="color-9A9A9A font-size24">{{noticeMsg.messageText|overstep}}</view>
							</view>
							<view class="uni-item-right">
								<view class="color-9A9A9A">{{noticeMsg.messageDate}}</view>
								<view class="height-50">
									<view v-show="isMessages" class="iconlabel">{{noticeMsg.messageCount}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 消息列表 -->
				<view class="message-list" v-if="recentlyList.length">
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item,index) in recentlyList" :options="options" :key="index" :isMargin=false
						 @click="operationMsg($event,item,index)">
							<view class="uni-swipe-action__content " @click="toSesscton(item,item.type)">
								<view class="item no-border-bottom" :class="{'stick' : item.stick}">
									<block v-if="item.type == 1">
										<view class="item-left">
											<view class="avator">
												<view class="iconfont ic_system-news"></view>
											</view>
										</view>
										<view class="item-middle">
											<text class="title">{{item.title}}</text>
											<text class="message">{{item.message}}</text>
										</view>
										<view class="item-right">
											<view class="time">{{item.time}}</view>
											<view class="height-50">
												<view class="mark" v-if="item.count>0">{{item.count}}</view>
											</view>
										</view>
									</block>
									<block v-else>
										<view class="item-left">
											<avator-group :type="item.type" :avator="item.url"></avator-group>
										</view>
										<view class="item-middle">
											<text class="title">{{item.title}}</text>
											<text class="message">{{item.message}}</text>
										</view>
										<view class="item-right">
											<view class="time">{{item.time}}</view>
											<view class="height-50">
												<view class="mark" v-if="item.count>0">{{item.count}}</view>
											</view>
										</view>
									</block>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>
			
			
			<!-- 通讯录页 -->
			<view v-if="TabCur3==1" class="example-body">
				<uni-indexed-list :options="lists" @userItem="toImChat" @searchInput="searchInput" ref="reEsearch" />
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import uniIndexedList from '@/components/uni-indexed-list/uni-indexed-list.vue'
	import WucTab from '@/components/wuc-tab/wuc-tab.vue';
	import jnpf from '@/common/js/jnpf.js'
	import helper from '@/common/js/helper.js'
	import config from '@/common/js/config.js'
	import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
	import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'
	import avatorGroup from "@/components/message/avator-group.vue"
	var that;
	export default {
		components: {
			
			uniIndexedList,
			uniSwipeAction,
			uniSwipeActionItem,
			avatorGroup,
			WucTab
		},
		data() {
			return {
				search: '',
				research: '',
				isHide: false,
				sesstion: '0',
				options: [{
						text: '已读',
						style: {
							backgroundColor: '#C7C6CD'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				badge: 0,
				height: 0,
				isMessage: true,
				isNotice: true,
				tabList3: [{
					name: '消息'
				}, {
					name: '通讯录'
				}],
				TabCur3: 0,
			};
		},
		filters: {
			overstep: function(value) {
				if (!value) return '';
				value = value.toString();
				if (value.length > 16) {
					return value.substring(0, 16) + '...';
				}
				return value;
			}
		},
		computed: {
			lists: function() { //用户索引列表
				try {
					let indexList = [];
					let userList = [];
					let research = this.research;
					let userDate = uni.getStorageSync(config.Global.cache + '_UserList');
					let apiKey = uni.getStorageSync('apiKey') || 'api';					let baseUrlObj = config.Global.baseUrl;
					let baseUrl = config.Global.baseUrl[apiKey].apiUrl;
					const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
					for (let i in userDate) {
						
						if (i != userProvider.id) {
							userDate[i].F_QuickQuery = userDate[i].quickQuery.substr(0, 1);
							userDate[i].headIcon = baseUrl + userDate[i].headIcon;
							userDate[i].realName = userDate[i].realName+"/"+userDate[i].account;
						}
						userList.push(userDate[i]);
					}
					if (research != '') {
						return userList.filter(function(product) {
							return Object.keys(product).some(function(key) {
								return String(product[key]).toLowerCase().indexOf(research) > -1
							})
						})
						return userList
					} else {
						let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
							"U", "V", "W", "X", "Y", "Z", "#"
						];
						for (let i in array) {
							let childNodes = helper.jsonFind(userList, function(v) {
								return v.F_QuickQuery == array[i]
							});
							if (childNodes.length > 0) {
								indexList.push({
									key: array[i],
									title: array[i],
									itemIndex: i,
									items: childNodes
								});
							}
						}
						return indexList;
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			recentlyList: function() {
				
				let _this = this;
				let search = this.search;
				const account = uni.getStorageSync(config.Global.cache + '_Account');
				const recentlyList = uni.getStorageSync(config.Global.cache + '_To_' + account + '_Recently');
				
				let messages = this.recentlys;
				
				messages = messages.length == 0 ? recentlyList : messages;
				let recentContact = [];
				let badge = 0;
				let apiKey = uni.getStorageSync('apiKey') || 'api';				let baseUrlObj = config.Global.baseUrl;
				let baseUrl = config.Global.baseUrl[apiKey].apiUrl;
				if (messages.length > 0) {
					
					for (let i = 0; i < messages.length; i++) {
						badge = badge + messages[i].count;
						let _user = jnpf.userData(messages[i].friendId);
						messages[i].url = [baseUrl + _user.F_HeadIcon];
						messages[i].title = _user.F_Name;
					}
				} else {
					// #ifndef MP-ALIPAY
					uni.removeTabBarBadge({
						index: 1,
					});
					// #endif
				}
				if (search) {
					return messages.filter(function(product) {
						return Object.keys(product).some(function(key) {
							return String(product[key]).toLowerCase().indexOf(search) > -1
						})
					})
				}
				_this.isMessage = this.noticeMsg.messageCount > 0 ? true : false;
				_this.isNotice = this.noticeMsg.noticeCount > 0 ? true : false;
				badge = badge + this.noticeMsg.messageCount + this.noticeMsg.noticeCount;
				_this.badge = badge;
				this.tabBarBadge(badge);
				return messages;
			},
			
			
			online: function() {
				return this.$store.state.wschat.online
			},
			offline: function() {
				return this.$store.state.wschat.offline
			},
			noticeMsg: function() {
				return this.$store.state.wschat.noticeMsgDef
			},
			isNotices: function() {
				return this.isNotice
			},
			isMessages: function() {
				return this.isMessage
			},
			recentlys: function() {
				return this.$store.state.wschat.recentlys;
			}
		},
		watch: {
			online() {},
			offline() {},
			noticeMsg() {},
			recentlyList() {},
			recentlys() {}
		},
		onLoad() {
			this.loadModal = false
			let badge = uni.getStorageSync(config.Global.cache + '_Badge')
			this.tabBarBadge(badge);
			
		},
		onShow() {
			
			let badge = uni.getStorageSync(config.Global.cache + '_Badge')
			this.noticeMsg.messageCount=badge
			this.tabBarBadge(badge);
		},
		onHide() {
			if (this.search != '') {
				this.search = '';
			}
			if (this.research != '') {
				this.$refs.reEsearch.reEsearch();
			}
		},
		methods: {
			/* tab切换 */
			tabChange(index) {
				
				this.search = '';
				this.research = '';
				this.TabCur3 = index;
			},
			
			/* 消息列表点击事件 */
			toSesscton(item, type) {
				
				try {
					const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
					if (item.friendId != '' && userProvider.id != '') {
						this.$store.state.wschat.messageList = null;
						const token = uni.getStorageSync(config.Global.cache + '_Token');
						
						if (token) {
							const msg = JSON.stringify({
								method: "MessageList",
								token: token,
								toUserId: item.friendId,
								formUserId: userProvider.id,
								currentPage: 1,
								pageSize: 15,
								sord: "desc"
							});
							helper.sendSocketMessage(msg);
						}
					}
					let _this = this;
					this.badge = this.badge - item.count;
					let friend = {
						friendHeadurl: item.url[0],
						friendNnick: item.title,
						friendId: item.friendId
					}
					this.$store.commit('setFriend', friend)
					let messages = that.recentlyList;
					let _recently = helper.jsonFind(messages, function(v) {
						return v.friendId == item.friendId
					});
					if (_recently.length > 0 && item.count > 0 && item.friendId != '') {
						const token = uni.getStorageSync(config.Global.cache + '_Token');
						if (token) {
							const msg = JSON.stringify({
								method: "UpdateReadMessage",
								token: token,
								formUserId: item.friendId
							});
							helper.sendSocketMessage(msg);
							const badge = uni.getStorageSync(config.Global.cache + '_Badge');
							let badgen = badge - item.count;
							uni.setStorage({
								key: config.Global.cache + '_Badge',
								data: badgen
							});
						}
						_recently[0].count = 0;
						this.$set(_recently[0], 'count', 0);
						this.$store.state.wschat.recentlys = messages;
					}
					const account = uni.getStorageSync(config.Global.cache + '_Account');
					if (account) {
						uni.setStorage({
							key: config.Global.cache + '_To_' + account + '_Recently',
							data: messages
						});
					}
					uni.navigateTo({
						url: '../instantmsg/im-chat/im-chat?name=' + item.title + '&friendId=' + item.friendId,
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
				} catch (e) {}
			},
			
			/* 通讯录列表点击事件 */
			toImChat(e) {
				
				// try {
				let _this = this;
				const token = uni.getStorageSync(config.Global.cache + '_Token');
				const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
				if (e.id != '' && userProvider.id != '') {
					this.$store.state.wschat.messageList = null;
					if (token) {
						const msg = JSON.stringify({
							method: "MessageList",
							token: token,
							toUserId: e.id,
							formUserId: userProvider.id,
							currentPage: 1,
							pageSize: 15,
							sord: "desc"
						});
						
						helper.sendSocketMessage(msg);
					}

				}
				let friend = {
					friendHeadurl: e.F_HeadIcon,
					friendNnick: e.F_Name,
					friendId: e.F_Id
				}
				this.$store.commit('setFriend', friend)
				const account = uni.getStorageSync(config.Global.cache + '_Account');
				uni.getStorage({
					key: config.Global.cache + '_To_' + account + '_Recently',
					success: (res) => {
						let messages = res.data;
						let _data = helper.jsonFind(messages, function(v) {
							return v.friendId == e.F_Id
						});
						if (_data.length > 0 && _data[0].count > 0 && e.F_Id != '') {
							if (token) {
								uni.sendSocketMessage({
									data: JSON.stringify({
										method: "UpdateReadMessage",
										token: token,
										formUserId: e.F_Id
									}),
									complete: (e) => {
										helper.start();
									}
								});
								const badge = uni.getStorageSync(config.Global.cache + '_Badge');
								let badgen = badge - _data[0].count;
								uni.setStorage({
									key: config.Global.cache + '_Badge',
									data: badgen
								});
							}
							_data[0].count = 0;
						}
						this.$store.state.wschat.recentlys = messages;
						const account = uni.getStorageSync(config.Global.cache + '_Account');
						if (account) {
							uni.setStorage({
								key: config.Global.cache + '_To_' + account + '_Recently',
								data: messages
							});
						}
					},
					fail: () => {}
				});
				uni.navigateTo({
					url: '../instantmsg/im-chat/im-chat?name=' + e.realName + '&friendId=' + e.id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
				// } catch (e) {}
			},
			
			/* 跳转通知公告页面 */
			noticeInfo() {
				uni.navigateTo({
					url: '/pages/message/instantmsg/notice/noticeInfo/noticeInfo',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			
			/* 跳转系统消息页面 */
			systemInfo() {
				uni.navigateTo({
					url: '/pages/message/instantmsg/system/systemInfo/systemInfo',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			
			
			// privateInfo() {
			// 	uni.navigateTo({
			// 		url: '/pages/message/instantmsg/private/privateInfo/privateInfo',
			// 		success: res => {},
			// 		fail: () => {},
			// 		complete: () => {}
			// 	});
			// },
			// addressbook() {
			// 	uni.navigateTo({
			// 		url: '/pages/message/instantmsg/addressbook/addressbook',
			// 		success: res => {},
			// 		fail: () => {},
			// 		complete: () => {}
			// 	});
			// },
			removeMsg: function(data) {
				this.messages = data;
			},
			/* 徽标 */
			tabBarBadge(badge) {
				// #ifndef MP-ALIPAY
				
				if (badge > 0) {
					uni.setTabBarBadge({
						index: 1,
						text: badge > 99 ? '99+' : badge.toString(),
					});
				} else {
					uni.removeTabBarBadge({
						index: 1,
					});
				}
				// #endif
			},
			/* 搜索框 */
			searchInput(e) {
				this.research = e;
			},
			
			operationMsg(e, item, index) {
				
				try {
					const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
					const account = uni.getStorageSync(config.Global.cache + '_Account');
					var _this = this;
					this.messageIndex = -1;
					switch (e.content.text) {
						case "删除":
							_this.recentlyList.splice(index, 1);
							if (account) {
								uni.setStorage({
									key: config.Global.cache + '_To_' + account + '_Recently',
									data: _this.recentlyList
								});
							}
							this.$store.state.wschat.recentlys = _this.recentlyList;
							break;
						case "已读":
							if (item.friendId != '' && item.count > 0) {
								item.count = 0;
								try {
									const token = uni.getStorageSync(config.Global.cache + '_Token');
									if (token) {
										const msg = JSON.stringify({
											method: "UpdateReadMessage",
											token: token,
											formUserId: item.friendId
										});
										helper.sendSocketMessage(msg);
										const badge = uni.getStorageSync(config.Global.cache + '_Badge');
										let badgen = badge - item.count;
										uni.setStorage({
											key: config.Global.cache + '_Badge',
											data: badgen
										});
									}
								} catch (e) {}
							}
							this.$store.state.wschat.recentlys = _this.recentlyList
							if (account) {
								uni.setStorage({
									key: config.Global.cache + '_To_' + account + '_Recently',
									data: _this.recentlyList
								});
							}
							break;
					}
				} catch (e) {
					//TODO handle the exception
				}
			}
		},
		mounted() {
			that = this;
			// 获取设备宽度
			uni.getSystemInfo({
				success: function(res) {
					that.height = res.windowHeight;
				}
			});
			// let search = uni.createSelectorQuery().select(".search-input");
			// search.boundingClientRect(data => {
			// 	_this.rows = Math.ceil((_this.height - data.height) / 58)
			// }).exec();
		}
	};
</script>

<style scoped="true" lang="scss">
	.floating-menus {
		position: fixed;
		top: 0;
		right: 20upx;
		z-index: 10;
		opacity: 0;
		transition: all 0.4s;
		height: 0;
		overflow: hidden;
	}

	.uni-input-placeholder {
		color: #9A9A9A;
	}

	.gongao-back {
		background: linear-gradient(-90deg, #FD966F, #FB5E66);
	}

	.xiaoxi-back {
		background: linear-gradient(-90deg, #FFE273, #FFB03A);
	}

	.floating-menus {
		&.show {
			opacity: 1;
			height: auto;
		}

		&.hidden {
			opacity: 0;
			height: 0;
		}
	}

	.search-input {
		background: #FFFFFF;
	}

	.uni-item-right {
		align-items: flex-end;
	}

	.mark {
		background-color: #FE5146;
		line-height: 35upx;
		text-align: center;
		font-size: 18upx;
		min-width: 35upx;
		min-height: 35upx;
		border-radius: 18upx;
		color: #fff;
	}

	.titleImg {
		width: 82upx;
		height: 82upx;
		border-radius: 50%;
	}

	.uni-list-cell {
		background: #FFFFFF;
	}

	.height-50 {
		height: 50rpx;
	}

	/* #ifndef MP */
	.message-list {
		.uni-swipe:last-child .item {
			border-bottom: none;
		}
	}

	/* #endif */

	.uni-swipe-action__content {
		width: 100%;

	}

	.item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		height: 128upx;
		align-items: center;
		background-color: #fff;
		// border-bottom: 1px solid #E6E6E6;
		position: relative;
		padding: 0 28upx;
		border-bottom: 0.5px solid #E3E3E5;

		&::after {
			content: "";
			position: absolute;
			z-index: 3;
			right: 30upx;
			bottom: 0;
			left: 28rpx;
			height: 1px;
			-webkit-transform: scaleY(.5);
			transform: scaleY(.5);
			background-color: #c8c7cc;
		}

		.item-left {
			display: flex;
			align-items: center;
		}

		&.stick {
			background-color: rgba(243, 236, 221, .5);
		}

		.item-middle {
			display: flex;
			flex: 1;
			flex-wrap: wrap;
			flex-direction: row;
			justify-content: flex-start;
			margin-left: 20upx;
			overflow: hidden;

			.title {
				width: 100%;
				color: #000;
				font-family: "微软雅黑";
				font-weight: 400;
				font-size: 28upx;
				height: 50upx;
				line-height: 50upx;
				overflow: hidden;
				/*自动隐藏文字*/
				text-overflow: ellipsis;
				/*文字隐藏后添加省略号*/
				white-space: nowrap;
				/**强制不换行*/
				color: #3A3A3A;
			}

			.message {
				width: 100%;
				font-family: "微软雅黑";
				color: #9A9A9A;
				height: 40upx;
				line-height: 40upx;
				font-size: 24upx;
				overflow: hidden;
				/**自动隐藏文字*/
				text-overflow: ellipsis;
				/**文字隐藏后添加省略号*/
				white-space: nowrap;
				/**强制不换行*/
			}
		}

		.item-right {
			overflow: hidden;
			display: flex;
			flex-direction: column;
			align-items: flex-end;

			.time {
				color: #808080;
				font-size: 26upx;
				height: 60upx;
				line-height: 60upx;
			}

			.mark {
				background-color: #FE5146;
				line-height: 35upx;
				text-align: center;
				font-size: 18upx;
				min-width: 35upx;
				min-height: 35upx;
				border-radius: 18upx;
				color: #fff;
				margin-left: 70upx;
			}
		}

		.height-50 {
			height: 50rpx;
		}
	}
</style>
